package com.qf.czh.vhr.config;

import com.qf.czh.vhr.entity.Hr;
import com.qf.czh.vhr.entity.Role;
import org.springframework.security.access.AccessDecisionManager;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Component;

import java.util.Collection;
import java.util.List;

@Component
public class MyDecision implements AccessDecisionManager {
    //将myfilter拿到的角色名list(即当前请求所需角色),与当前用户具有的角色名进行比对.看用户是否 具有所需角色
    @Override
    public void decide(Authentication authentication, Object object, Collection<ConfigAttribute> configAttributes) throws AccessDeniedException, InsufficientAuthenticationException {
       //authorities 获取用户所具有的角色.与下面这个一致
        // 这个一致: Collection<? extends GrantedAuthority> authorities1 = ((Hr) authentication.getPrincipal()).getAuthorities();
        //authorities  用户所具有的角色s
        Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
        //configAttributes myfilter返回值,当前请求所需角色,
        //循环拿出里面每一所需个角色
        for (ConfigAttribute configAttribute : configAttributes) {
            //每个所需角色转成String才能够equals
            String attribute = configAttribute.getAttribute();
            //首先判断特殊清空,如果匹配ROLE_LOGIN 又是匿名,就抛异常.
            if ("ROLE_LOGIN".equals(attribute)) {
                if (authentication instanceof AnonymousAuthenticationToken) {
                    throw new AccessDeniedException("没有登录,去登录");
                } else {
                    //其他情况就是有登录的.例如rememberme,就可以中断执行.该干嘛干嘛
                    //进来这里其实就是该请求不在菜单列表上,没有所需角色,但用户又登录了.
                    return;
                }
            }
            //authorities 用户所具有的角色s
            //拿出每个用户具有的角色与每个请求所需角色进行比对
            for (GrantedAuthority authority : authorities) {
                //比对上了.证明用户具有请求所需角色,return 该干嘛干嘛.
                if (authority.getAuthority().equals(attribute)) {
                    return;
                }
            }

        }

        //如果每个用户具有角色与请求所需角色一个都匹配不是,就抛异常
        throw  new AccessDeniedException("权限不足,");
    }

    @Override
    public boolean supports(ConfigAttribute attribute) {
        return true;
    }

    @Override
    public boolean supports(Class<?> clazz) {
        return true;
    }
}
